import 'dart:ui' as ui;
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:shop/test/widget/ImageClipper.dart';

const String pic =
    'http://pic75.nipic.com/file/20150821/9448607_145742365000_2.jpg';

class ClipImageScreen extends StatefulWidget {
  @override
  _ClipImageScreenState createState() => _ClipImageScreenState();
}

class _ClipImageScreenState extends State<ClipImageScreen> {
  ImageClipper clipper;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ImageClipper'),
      ),
      body: Center(
        child: Column(
          children: [
            SizedBox(
              child: Container(color: Colors.grey, child: Image.network(pic,fit: BoxFit.fill,)),
              width: 200,
              height: 150,
            ),
            SizedBox(
              height: 50,
            ),
            Container(
                color: Colors.green,
                child: CustomPaint(
                  painter: clipper,
                  size: Size(200, 200),
                )),
            RaisedButton(child: Text('Clip'), onPressed: () => clip())
          ],
        ),
      ),
    );
  }

  Future _loadImge() async {
    ImageStream imageStream = NetworkImage(pic).resolve(ImageConfiguration());
    Completer completer = Completer();
    void imageListener(ImageInfo info, bool synchronousCall) {
      ui.Image image = info.image;
      completer.complete(image);
      imageStream.removeListener(ImageStreamListener(imageListener));
    }

    imageStream.addListener(ImageStreamListener(imageListener));
    return completer.future;
  }

  clip() async {
    ui.Image uiImage;
    _loadImge().then((image){uiImage = image;}).whenComplete(() {
      clipper = ImageClipper(uiImage);
      setState(() {});
    });
  }
}
